package com.xmtlxx.web.controller.tms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.xmtlxx.tms.domain.*;
import com.xmtlxx.tms.domain.vo.*;
import com.xmtlxx.tms.mapper.*;
import com.xmtlxx.web.controller.center.service.ICommonService;
import com.xmtlxx.web.controller.tms.service.IOrderService;
import com.xmtlxx.web.controller.wms.service.IDealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysDept;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.enums.PropertyLogNode;
import com.xmtlxx.common.enums.PropertyLogType;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.tengbo.PushDatasUtil;
import com.xmtlxx.common.tengbo.vo.PropertyLogModelsVo;
import com.xmtlxx.common.utils.DateUtils;
import com.xmtlxx.common.utils.JsonUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.OperatorLog;
import com.xmtlxx.oms.domain.PropertyLog;
import com.xmtlxx.oms.domain.vo.TaskVo;
import com.xmtlxx.oms.mapper.OperatorLogMapper;
import com.xmtlxx.oms.mapper.PropertyLogMapper;
import com.xmtlxx.oms.mapper.TaskMapper;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.mapper.SysDeptMapper;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.system.mapper.SysUserMapper;
import com.xmtlxx.tms.domain.bo.OrderBo;
import com.xmtlxx.tms.domain.bo.OrderDtlBo;
import com.xmtlxx.wms.domain.bo.DealBo;
import com.xmtlxx.wms.domain.vo.DealVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OrderServiceImpl implements IOrderService {

    private final OrderMapper baseMapper;

    private final OrderDtlMapper orderDtlMapper;

    private final LinesMapper linesMapper;

    private final CarMapper carMapper;

    private final OperatorLogMapper logMapper;

    private final WaybillMapper waybillMapper;

    private final WaybillDtlMapper waybillDtlMapper;

    private final DriverMapper driverMapper;

    private final ClientMapper clientMapper;

    private final SysOssMapper ossMapper;

    private final WaybillLogMapper waybillLogMapper;

    private final CarrierMapper carrierMapper;

    private final SysUserMapper userMapper;


    private final PropertyLogMapper propertyLogMapper;


    private final TaskMapper taskMapper;

    private final SysDeptMapper deptMapper;

    private final ICommonService commonService;

    private final IDealService dealService;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderVo queryById(String id){
        //return baseMapper.selectVoById(id);
        return baseMapper.selectOrderVoByID(id);
    }

    @Override
    public OrderVo queryByTaskId(String id) {
        OrderVo vo = null;
        OrderBo orderBo = new OrderBo();
        orderBo.setTaskId(id);
        orderBo.setDelFlag("0");
        List<OrderVo> orderVos = baseMapper.selectOrder(orderBo);
        if(orderVos != null && orderVos.size() > 0){
            vo = orderVos.get(0);
        }
        return vo;
    }

    /**
     * 查询订单列表
     *
     * @param bo 订单
     * @return 订单
     */
    @Override
    public TableDataInfo<OrderVo> queryPageList(OrderBo bo, PageQuery pageQuery) {
       // LambdaQueryWrapper<Order> lqw = buildQueryWrapper(bo);
       // Page<OrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<OrderVo> result = baseMapper.selectPageOrderList(pageQuery.build(), bo);
        if(result != null && result.getRecords() != null && result.getRecords().size() > 0){
            result.getRecords().stream().forEach(item->{
                item.setChecked(false);
                if(LoginHelper.getLoginUser().getRolePermission().contains("smscys")){
                    item.setIsDispatch(true);
                }else {
                    item.setIsDispatch(false);
                }
                //车辆单
                if(item.getBuss().equals("1")){
                    List<OrderDtlVo> dtls = orderDtlMapper.selectOrderDtls(item.getId());
                    item.setCharacter(dtls.get(0).getCharacter());
                }

                if(item.getType().equals("2")){
                    DealBo dealBo = new DealBo();
                    dealBo.setTaskId(item.getTaskId());
                    List<DealVo> dealVo = dealService.queryList(dealBo);
                    final boolean[] isCheck = {true};
                    if(dealVo != null && dealVo.size() > 0){
                        dealVo.forEach(deal->{
                            if(!deal.getIsCheck().equals("1")){
                                isCheck[0] = false;
                            }
                        });
                        if(isCheck[0]){
                            item.setIsCheck("1");
                        }
                    }
                }
            });

        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询订单列表
     *
     * @param bo 订单
     * @return 订单
     */
    @Override
    public List<OrderVo> queryList(OrderBo bo) {
       // LambdaQueryWrapper<Order> lqw = buildQueryWrapper(bo);
       // return baseMapper.selectVoList(lqw);
        return baseMapper.selectOrderList(bo);
    }

    private LambdaQueryWrapper<Order> buildQueryWrapper(OrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Order> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeptId() != null, Order::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), Order::getOrderNo, bo.getOrderNo());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskId()), Order::getTaskId, bo.getTaskId());
        lqw.eq(StringUtils.isNotBlank(bo.getObjId()), Order::getObjId, bo.getObjId());
        lqw.eq(StringUtils.isNotBlank(bo.getFid()), Order::getFid, bo.getFid());
        lqw.eq(StringUtils.isNotBlank(bo.getEntrustNo()), Order::getEntrustNo, bo.getEntrustNo());
        lqw.eq(bo.getOrderSerial() != null, Order::getOrderSerial, bo.getOrderSerial());
        lqw.eq(StringUtils.isNotBlank(bo.getSourceType()), Order::getSourceType, bo.getSourceType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Order::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), Order::getType, bo.getType());
        lqw.eq(bo.getSignTime() != null, Order::getSignTime, bo.getSignTime());
        lqw.eq(bo.getCancelTime() != null, Order::getCancelTime, bo.getCancelTime());
        lqw.eq(bo.getDeliveryTime() != null, Order::getDeliveryTime, bo.getDeliveryTime());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliveryType()), Order::getDeliveryType, bo.getDeliveryType());
        lqw.eq(bo.getArriveTime() != null, Order::getArriveTime, bo.getArriveTime());
        lqw.eq(StringUtils.isNotBlank(bo.getClientId()), Order::getClientId, bo.getClientId());
        lqw.like(StringUtils.isNotBlank(bo.getClientName()), Order::getClientName, bo.getClientName());
        lqw.eq(StringUtils.isNotBlank(bo.getClientContacts()), Order::getClientContacts, bo.getClientContacts());
        lqw.eq(StringUtils.isNotBlank(bo.getSendAddress()), Order::getSendAddress, bo.getSendAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getSendContacts()), Order::getSendContacts, bo.getSendContacts());
        lqw.eq(bo.getSendDate() != null, Order::getSendDate, bo.getSendDate());
        lqw.eq(StringUtils.isNotBlank(bo.getSendAddr()), Order::getSendAddr, bo.getSendAddr());
        lqw.eq(StringUtils.isNotBlank(bo.getTakeAddr()), Order::getTakeAddr, bo.getTakeAddr());
        lqw.eq(StringUtils.isNotBlank(bo.getTakeContacts()), Order::getTakeContacts, bo.getTakeContacts());
        lqw.eq(bo.getTakeDate() != null, Order::getTakeDate, bo.getTakeDate());
        lqw.eq(StringUtils.isNotBlank(bo.getTakeTel()), Order::getTakeTel, bo.getTakeTel());
        lqw.eq(bo.getDispatcherId() != null, Order::getDispatcherId, bo.getDispatcherId());
        lqw.eq(StringUtils.isNotBlank(bo.getLineId()), Order::getLineId, bo.getLineId());
        lqw.like(StringUtils.isNotBlank(bo.getLineName()), Order::getLineName, bo.getLineName());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverId()), Order::getDriverId, bo.getDriverId());
        lqw.like(StringUtils.isNotBlank(bo.getDriverName()), Order::getDriverName, bo.getDriverName());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverPhone()), Order::getDriverPhone, bo.getDriverPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getCarNumber()), Order::getCarNumber, bo.getCarNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getCarId()), Order::getCarId, bo.getCarId());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), Order::getCreateBy, bo.getCreateBy());
        lqw.eq(bo.getCreateTime() != null, Order::getCreateTime, bo.getCreateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Order::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增订单
     *
     * @param bo 订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderVo insertByBo(OrderBo bo) {
        Order add = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(add);
        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");

        List<OrderDtl> dtls = new ArrayList<>();
        if(bo.getItems() != null && bo.getItems().size() > 0){
            dtls = bo.getItems().stream().map(item->{
                OrderDtl dtl = BeanUtil.toBean(item,OrderDtl.class);
                dtl.setId(IdUtil.simpleUUID());
                dtl.setOrderId(add.getId());
                dtl.setStatus("0");
                dtl.setDelFlag("0");
                return dtl;
            }).collect(Collectors.toList());

            orderDtlMapper.insertBatch(dtls);
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        /**
         * 操作日志
         */
        commonService.saveOperatorLog(StringUtils.isNotEmpty(add.getTaskId())?add.getTaskId():add.getId(),"tms","创建订单");

        OrderVo vo = new OrderVo();
        BeanUtil.copyProperties(add,vo);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean inserAllByBo(OrderBo bo) {
        boolean flag = false;
        //新增合并订单
        Order add = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(add);
        add.setId(IdUtil.simpleUUID());
        add.setOrderNo(getNo());
        add.setStatus("2");
        add.setDelFlag("0");
        add.setType("2");//合并单
        add.setNums(0l);
        add.setVolume(new BigDecimal(0));
        add.setWeight(new BigDecimal(0));
        add.setLineName(linesMapper.selectById(bo.getLineId()).getName());
        add.setCarNumber(carMapper.selectById(bo.getCarId()).getCarNumber());
        add.setIsStaging("0");

        //原订单增加父级id
        if(bo.getOrderIds() != null && bo.getOrderIds().size() > 0){
            for (String id :bo.getOrderIds()){
                Order order = baseMapper.selectById(id);
                order.setFid(add.getId());
                order.setStatus("2");//设置为运输中
                baseMapper.updateById(order);
            }
        }


        List<OrderDtl> orderDtls = new ArrayList<>();
        //处理财物清单
        if(bo.getItems() != null && bo.getItems().size() > 0){
            orderDtls = bo.getItems().stream().map(item->{
                OrderDtl dtl = new OrderDtl();
                BeanUtil.copyProperties(item,dtl);
                dtl.setId(IdUtil.simpleUUID());
                dtl.setOrderId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");
                return dtl;
            }).collect(Collectors.toList());
        }
        if(orderDtls != null && orderDtls.size() > 0){
            orderDtlMapper.insertBatch(orderDtls);
        }
        flag = baseMapper.insert(add) > 0;

        //新增运单
        Waybill waybill =new Waybill();
        waybill.setId(IdUtil.simpleUUID());
        waybill.setOrderId(add.getId());
        waybill.setWaybillNo(getwaybillNo());
        waybill.setDispatchTime(new Date());
        waybill.setStatus("0");
        waybill.setDelFlag("0");

        waybill.setCarId(bo.getCarId());
//        waybill.setCarNumber(bo.getCarNumber());
        waybill.setCarNumber(carMapper.selectById(bo.getCarId()).getCarNumber());
        waybill.setDriverId(bo.getDriverId());
        waybill.setDriverName(bo.getDriverName());
        waybill.setVolume(new BigDecimal("0"));
        waybill.setWeight(new BigDecimal("0"));
        waybill.setScheduleId(bo.getScheduleId());

        flag = waybillMapper.insert(waybill)>0;

        List<WaybillDtl> waybillDtls = orderDtls.stream().map(item->{
            WaybillDtl dtl = new WaybillDtl();
            BeanUtil.copyProperties(item,dtl,"id");
            dtl.setId(IdUtil.simpleUUID());
            dtl.setWaybillId(waybill.getId());
            dtl.setOrderDtlId(item.getId());
            dtl.setDelFlag("0");
            dtl.setStatus("0");
            return dtl;
        }).collect(Collectors.toList());

        if(waybillDtls != null && waybillDtls.size() > 0){
            waybillDtlMapper.insertBatch(waybillDtls);
        }
        return flag;
    }

    /**
     * 修改订单
     *
     * @param bo 订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderVo updateByBo(OrderBo bo) {
        Order update = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(update);
        Long nums = update.getNums();


        /**
         * 查询原明细数据
         */
        OrderDtlBo dtlBo = new OrderDtlBo();
        dtlBo.setOrderId(update.getId());
        List<OrderDtlVo> olds = orderDtlMapper.selectOrderDtlList(dtlBo);

        List<OrderDtl> dtls = new ArrayList<>();

        if(bo.getItems() != null && bo.getItems().size() > 0){
            dtls = bo.getItems().stream().map(item->{
                OrderDtl dtl = new OrderDtl();
                BeanUtil.copyProperties(item,dtl);
                if(StringUtils.isEmpty(dtl.getId())){//修改后的物品
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setDelFlag("0");
                    dtl.setStatus("0");
                    dtl.setOrderId(update.getId());
                }
                /**
                 * 迭代查询移除的明细
                 */
                Iterator iterator = olds.iterator();
                while(iterator.hasNext()){
                    OrderDtlVo orderDtl = (OrderDtlVo) iterator.next();
                    if(orderDtl.getId().equals(dtl.getId())){
                        iterator.remove();
                    }
                }

                return dtl;
            }).collect(Collectors.toList());

            nums = dtls.stream().mapToLong(item-> item.getNums()).sum();
        }
        update.setNums(nums);

        if(dtls.size() > 0){
            orderDtlMapper.insertOrUpdateBatch(dtls);
        }
        //已删除的物品处理：删除dtl表、回退可移交状态
        if(olds != null && olds.size() > 0){
            olds.forEach(item -> {
                orderDtlMapper.deleteVoById(item.getId());
            });
        }

        //全车外观正前
        if(bo.getFacadeOss() != null && bo.getFacadeOss().size() > 0){
            for (SysOss oss:bo.getFacadeOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("facade");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //全车外观正左
        if(bo.getFacadeLeftOss() != null && bo.getFacadeLeftOss().size() > 0){
            for (SysOss oss:bo.getFacadeLeftOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("facadeLeft");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //全车外观正后
        if(bo.getFacadeAfterOss() != null && bo.getFacadeAfterOss().size() > 0){
            for (SysOss oss:bo.getFacadeAfterOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("facadeAfter");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //全车外观正右
        if(bo.getFacadeRightOss() != null && bo.getFacadeRightOss().size() > 0){
            for (SysOss oss:bo.getFacadeRightOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("facadeRight");
                ossMapper.insertOrUpdate(sysOss);
            }
        }

        //仪表盘
        if(bo.getDashboardOss() != null && bo.getDashboardOss().size() > 0){
            for (SysOss oss:bo.getDashboardOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("dashboard");
                ossMapper.insertOrUpdate(sysOss);
            }
        }

        //车架号
        if(bo.getCarOss() != null && bo.getCarOss().size() > 0){
            for (SysOss oss:bo.getCarOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("carNumber");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //车钥匙
        if(bo.getCarKeyOss() != null && bo.getCarKeyOss().size() > 0){
            for (SysOss oss:bo.getCarKeyOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("carKey");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //行驶证
        if(bo.getDriveLicenOss() != null && bo.getDriveLicenOss().size() > 0){
            for (SysOss oss:bo.getDriveLicenOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("driveLicen");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //登记证书
        if(bo.getRegisterBookOss() != null && bo.getRegisterBookOss().size() > 0){
            for (SysOss oss:bo.getRegisterBookOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("registerBook");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //交接现场
        if(bo.getHandoverOss() != null && bo.getHandoverOss().size() > 0){
            for (SysOss oss:bo.getHandoverOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("handover");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //装车
        if(bo.getLoadOss() != null && bo.getLoadOss().size() > 0){
            for (SysOss oss:bo.getLoadOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("load");
                ossMapper.insertOrUpdate(sysOss);
            }
        }

        //瑕疵
        if(bo.getFlawOss() != null && bo.getFlawOss().size() > 0){
            for (SysOss oss:bo.getFlawOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("flaw");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //目的地
        if(bo.getTakeOss() != null && bo.getTakeOss().size() > 0){
            for (SysOss oss:bo.getTakeOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("take");
                ossMapper.insertOrUpdate(sysOss);
            }
        }//卸车
        if(bo.getUnloadOss() != null && bo.getUnloadOss().size() > 0){
            for (SysOss oss:bo.getUnloadOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("unload");
                ossMapper.insertOrUpdate(sysOss);
            }
        }
        //其他
        if(bo.getOtherOss() != null && bo.getOtherOss().size() > 0){
            for (SysOss oss:bo.getOtherOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("other");
                ossMapper.insertOrUpdate(sysOss);
            }
        }

        //其他(到达）
        if(bo.getOtherTwoOss() != null && bo.getOtherTwoOss().size() > 0){
            for (SysOss oss:bo.getOtherTwoOss()){
                SysOss sysOss = new SysOss();
                BeanUtil.copyProperties(oss,sysOss);
                sysOss.setObjid(update.getId());
                sysOss.setBuss("otherTwo");
                ossMapper.insertOrUpdate(sysOss);
            }
        }

        baseMapper.updateById(update);

        OrderVo vo = new OrderVo();
        BeanUtil.copyProperties(update,vo);

        return vo;
    }

    @Override
    public Boolean updateByOrder(OrderBo bo) {
        Order update = BeanUtil.toBean(bo, Order.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Order entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    public String getNo(){
        LambdaQueryWrapper<Order> lqw = Wrappers.lambdaQuery();
        Long maxNumObject = baseMapper.selectCount(lqw);
        String num = "";
        String todayStr = DateUtils.date2String(new Date(), "yyMMdd");

        if (maxNumObject == null) {
            num = todayStr + "000001";
        } else {
            String maxnumStr = "00000" + maxNumObject.toString();
            String maxnumNo = maxnumStr.substring(maxnumStr.length() - 6, maxnumStr.length());
            String nextnumNo = StringUtils.nextNo(maxnumNo, 6);
            num = todayStr + nextnumNo;
        }
        return num;
    }

    public String getwaybillNo(){
        LambdaQueryWrapper<Waybill> lqw = Wrappers.lambdaQuery();
        Long maxNumObject = waybillMapper.selectCount(lqw);
        String num = "";
        String todayStr = DateUtils.date2String(new Date(), "yyMMdd");

        if (maxNumObject == null) {
            num = todayStr + "000001";
        } else {
            String maxnumStr = "00000" + maxNumObject.toString();
            String maxnumNo = maxnumStr.substring(maxnumStr.length() - 6, maxnumStr.length());
            String nextnumNo = StringUtils.nextNo(maxnumNo, 6);
            num = todayStr + nextnumNo;
        }
        return num;
    }

    /**
     * 初始化暂存派车
     * @param ids
     * @return
     */
    @Override
    public Map<String,Object> getOrderByDtls(String[] ids) {
        Map<String,Object> data = new HashMap<>();
        List<OrderVo> orders = new ArrayList<>();
        List<OrderDtlVo> dtls = new ArrayList<>();
        OrderVo vo = new OrderVo();
        if (ids != null && ids.length > 0){
            for (String id:ids){

                orders.add(baseMapper.selectOrderVoByID(id));

                List<OrderDtlVo> orderDtls = orderDtlMapper.selectVoList(new LambdaQueryWrapper<OrderDtl>()
                    .eq(OrderDtl::getOrderId,id));

                if (orderDtls != null && orderDtls.size()>0){
                    List<OrderDtlVo> vos = orderDtls.stream().map(item->{
                        OrderDtlVo dtl = new OrderDtlVo();
                        BeanUtil.copyProperties(item,dtl,"id");
                        return dtl;
                    }).collect(Collectors.toList());

                    if(dtls != null && dtls.size() > 0){
                        dtls.addAll(vos);
                    }else {
                        dtls = vos;
                    }
                }
            }
        }

        if(orders != null && orders.size() > 0){
            OrderVo enty = orders.get(0);
            vo.setOrderNo(getNo());
            vo.setDeptId(enty.getStagingDept() != null?enty.getStagingDept():null);
            ClientVo clientVo = clientMapper.selectClientVoByDeptId(enty.getStagingDept());
            if(clientVo != null){
                vo.setClientId(clientVo.getId());
                vo.setClientContacts(clientVo.getContacts());
                vo.setClientTel(clientVo.getTel());
                vo.setClientName(clientVo.getName());

                vo.setSendAddr(clientVo.getDeptName());
                vo.setSendAddress(clientVo.getAddress());
                vo.setSendTel(clientVo.getTel());
                vo.setSendContacts(clientVo.getContacts());
                vo.setSendLat(clientVo.getLat());
                vo.setSendLng(clientVo.getLng());
            }
        }
        vo.setItems(dtls);
        data.put("vo",vo);
        data.put("orders",orders);
        return data;
    }

    //日志添加
    public void  addOperatorLog(String objid,String type,String content){
        OperatorLog log = new OperatorLog();
        log.setId(IdUtil.simpleUUID());
        log.setObjid(objid);
        log.setDelFlag("0");
        log.setLogTime(new Date());
        log.setUserId(LoginHelper.getUserId());
        log.setOperator(LoginHelper.getNickname());
        log.setLogType(type);
        log.setContent(content);
        logMapper.insert(log);
    }

    public String getWaybillNo(){
        LambdaQueryWrapper<Waybill> lqw = Wrappers.lambdaQuery();
        Long maxNumObject = waybillMapper.selectCount(lqw);
        String num = "";
        String todayStr = DateUtils.date2String(new Date(), "yyMMdd");

        if (maxNumObject == null) {
            num = todayStr + "000001";
        } else {
            String maxnumStr = "00000" + maxNumObject.toString();
            String maxnumNo = maxnumStr.substring(maxnumStr.length() - 6, maxnumStr.length());
            String nextnumNo = StringUtils.nextNo(maxnumNo, 6);
            num = todayStr + nextnumNo;
        }
        return num;
    }

    @Override
    public List<OrderVo> orderStatistics() {
        return baseMapper.orderStatistics();
    }

    @Override
    public Boolean insertDispatch(DispatchVo vo) {
        String buss = PropertyLogType.DISPATCH.getCode();
        String storeId = null;
        boolean flag = false;
        String[] ignoreProperties = {"id","createBy","createTime","updateBy","updateTime"};
        //生成新的订单
        Order bo = new Order();
        bo.setId(IdUtil.simpleUUID());
        bo.setDelFlag("0");
        bo.setStatus("2");//运输中
        bo.setOrderNo("Z"+getNo());//转派订单编号
        bo.setIsStaging("0");
        bo.setSourceType("0");
        bo.setCarId(vo.getCarId());
        bo.setCarNumber(vo.getCarNumber());
        bo.setDispatcherId(LoginHelper.getUserId());//调度员
        //配送时间
        bo.setDeliveryTime(new Date());
        OrderVo oldOrder = baseMapper.selectVoById(vo.getOrderId());
        //寄件单位
        bo.setDeptId(LoginHelper.getDeptId());
        //收件信息
        if(oldOrder != null){
            bo.setTakeAddr(oldOrder.getTakeAddr());
            bo.setTakeAddress(oldOrder.getTakeAddress());
            bo.setTakeContacts(oldOrder.getTakeContacts());
            bo.setTakeTel(oldOrder.getTakeTel());

            bo.setBuss(oldOrder.getBuss());

            TaskVo task = taskMapper.selectTaskVoByID(oldOrder.getTaskId());
            storeId = task.getStoreId();
        }
        //寄件信息
        CarrierVo carrierVo = carrierMapper.selectVoOne(new LambdaQueryWrapper<Carrier>().eq(Carrier::getDeptId,LoginHelper.getDeptId()));
        if(carrierVo != null){
            bo.setSendAddr(carrierVo.getDeptName());
            bo.setSendContacts(carrierVo.getContacts());
            bo.setSendTel(carrierVo.getContactsTel());
            bo.setCarrierDeptId(LoginHelper.getDeptId());
        }
        bo.setType("4");//转派单
        bo.setPickupId(vo.getPickupId());//取件人
        bo.setDispatchId(vo.getPickupId());//派件人

        //处理物品明细
        String finalStoreId = storeId;
        List<OrderDtl> dtlItems = vo.getOrderDtlItems().stream().map(item->{
            OrderDtl dtl = new OrderDtl();
            BeanUtil.copyProperties(item,dtl,ignoreProperties);
            dtl.setId(IdUtil.simpleUUID());
            dtl.setOrderId(bo.getId());
            dtl.setStatus("0");

            saveLog(dtl,finalStoreId,bo.getId(),bo.getDeptId(),"重新派送",buss,null);

            return dtl;
        }).collect(Collectors.toList());
        flag = orderDtlMapper.insertBatch(dtlItems);

        //处理原订单与新订单关系
        List<Order> voList = vo.getOrdersItems().stream().map(item->{
            Order enty = new Order();
            BeanUtil.copyProperties(item,enty);
            enty.setFid(bo.getId());//设置上级id,关联到最新订单
            enty.setIsStaging("2");//0-未暂存 1-已暂存 2-已移交
            return enty;
        }).collect(Collectors.toList());
        flag = baseMapper.updateBatchById(voList);
        //物品数量
        Long onums = dtlItems.stream().mapToLong(item-> item.getNums()).sum();
        bo.setNums(onums);
        flag = baseMapper.insert(bo) > 0;
        addOperatorLog(StringUtils.isNotEmpty(bo.getTaskId())?bo.getTaskId():bo.getId(),"tms","创建转派订单");

        //转派运单生成
        Waybill waybill = new Waybill();
        waybill.setId(IdUtil.simpleUUID());
        waybill.setDelFlag("0");
        waybill.setOrderId(bo.getId());
        waybill.setWaybillNo("Z"+getWaybillNo());
        //车牌号
        waybill.setCarNumber(vo.getCarNumber());
        waybill.setCarId(vo.getCarId());
        //调度员
        waybill.setDispatcherId(bo.getDispatcherId());
        waybill.setDispatcher(userMapper.selectUserById(bo.getDispatcherId()).getNickName());
        //设置派单时间
        waybill.setDispatchTime(new Date());
        //设置接单时间
        waybill.setTakeBillTime(new Date());
        waybill.setBuss(bo.getBuss());
        //设置为待发车
        waybill.setStatus("2");
        //司机
        waybill.setDriverName(userMapper.selectUserById(vo.getPickupId()).getNickName());
        //承运商
        waybill.setCarrierId(carrierVo.getId());


        List<WaybillDtl> wdtlItems = dtlItems.stream().map(item->{
            WaybillDtl dtl = new WaybillDtl();
            BeanUtil.copyProperties(item,dtl,ignoreProperties);
            dtl.setId(IdUtil.simpleUUID());
            dtl.setOrderDtlId(item.getId());
            dtl.setWaybillId(waybill.getId());
            dtl.setStatus("0");
            return dtl;
        }).collect(Collectors.toList());
        flag = waybillDtlMapper.insertBatch(wdtlItems);

        //物品数量
        Long nums = wdtlItems.stream().mapToLong(item-> item.getNums()).sum();
        waybill.setNums(nums.intValue());
        flag = waybillMapper.insert(waybill) > 0;

        return flag;
    }

    //财物日志添加
    private  void  saveLog(OrderDtl dtl, String storeId, String objid, Long deptId, String content,String buss,List<SysOss> osses){
        PropertyLog propertyLog = new PropertyLog();

        BeanUtil.copyProperties(dtl,propertyLog,"id");
        propertyLog.setId(IdUtil.simpleUUID());
        propertyLog.setObjid(objid);
        propertyLog.setDeptId(deptId);
        propertyLog.setLogTime(new Date());
        propertyLog.setStoreId(storeId);
        propertyLog.setLogType(buss);//0-移交登记 1-入库 2-出库 3-调用 4-处置 5-交接 6-上架 7-挑拣
        propertyLog.setContent(content);
        propertyLog.setReceiveDept(LoginHelper.getDeptId());
        propertyLog.setUserId(LoginHelper.getUserId());
        propertyLog.setOperator(LoginHelper.getNickname());
        propertyLog.setInfo(JsonUtils.toJsonString(dtl));
        propertyLog.setDelFlag("0");

        SysDept dept = deptMapper.selectById(LoginHelper.getDeptId());

        propertyLog.setNode(PropertyLogNode.getNodeCodeByBuss(dept.getLevel(),"5"));
        int i =  propertyLogMapper.insert(propertyLog);
        if(osses != null && osses.size() > 0){
            for(SysOss oss : osses){
                SysOss copyOss = new SysOss();
                BeanUtil.copyProperties(oss,copyOss,"ossId");
                copyOss.setObjid(propertyLog.getId());
                copyOss.setBuss("propertyLog");
                ossMapper.insert(copyOss);
            }
        }

        if(i> 0 ){
            PropertyLogModelsVo data = new PropertyLogModelsVo();
            data.setApi("proBase");
            data.setData(propertyLogMapper.selectVoById(propertyLog.getId()));
            PushDatasUtil.pushPropertyDatas(data);
        }
    }
}
